util = {
    backlist_file_path = 'conf/ngx-lua/backlist.log'
}
-- 获取ip
function util.get_client_ip()
    local ip = ngx.req.get_headers()['x_forwarded_for']
    if not ip then
        ip = ngx.var.remote_addr
    else
        ip = ngx.re.gsub(ip, ',.*', '')
    end
    return ip
end

-- 获取根据cookie Key 获取 value
function util.get_cookie_by_key(key)
    local cookies = ngx.req.get_headers()['cookie']
    if not cookies then
        return ''
    end
    cookies = util.split_string(cookies, ';')
    tmp_cookies = {}
    for i, j in ipairs(cookies) do
        cookie = cookies[i]
        cookie = util.split_string(cookie, '=')
        if string.gsub(cookie[1], ' ', '') == key then
            return string.gsub(cookie[2], ' ', '')
        end
    end
    return ''
end

-- 分割字符串
function util.split_string(str, delimiter)
    if str == nil or str == '' or delimiter == nil then
        return nil
    end
    local result = {}
    for match in (str .. delimiter):gmatch('(.-)' .. delimiter) do
        table.insert(result, match)
    end
    return result
end

-- 加载黑名单
function util.load_backlist()
    -- 从文件中加载
    file_path = util.backlist_file_path
    local backlist = {}
    file = io.open(file_path)
    if not file then
        os.execute("echo ''>" .. file_path)
    end
    for line in io.lines(file_path) do
        line = string.gsub(line, "\r", '')
        if line ~= "''" then
            backlist[#backlist + 1] = string.gsub(line, ' ', '')
        end
    end
    return backlist
end

-- 写进黑名单
function util.write_backlist(back)
    file_path = util.backlist_file_path
    file = io.open(file_path, 'a+')
    io.output(file)
    io.write(back .. "\r")
    io.close(file)
end

--进入黑名单执行的动作
function util.exit(type)
    ngx.say('<p style="color:red;">' .. type .. ':' .. ',中枪了</p>')
    ngx.exit(ngx.HTTP_FORBIDDEN)
end

